package swardToOffer.struct_2_string;

/**
 * @Author ChanZany
 * @Date 2021/5/26 18:34
 * @Version 1.0
 面试题58（一）：翻转单词顺序
 题目：输入一个英文句子，翻转句子中单词的顺序，但单词内字符的顺序不变。
 为简单起见，标点符号和普通字母一样处理。例如输入字符串"I am a student. "，
 则输出"student. a am I"。
解法1:字符串切分逆序重组
解法2:双指针
 */
public class ReverseWordsInSentence {

    public String reverseWords(String s) {
        s = s.trim(); // 删除首尾空格
        int left = s.length()-1 ;
        int right =left;
        StringBuilder sb = new StringBuilder();
        while (left>=0){
            while (left>=0 && s.charAt(left) !=' ') left--;
            sb.append(s, left+1, right+1).append(" ");
            while (left>=0 && s.charAt(left)==' ') left--;
            right=left;
        }
        return sb.toString().trim();
    }
    public String reverseWords2(String s) {
        s = s.trim();
        String[] splits = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = splits.length-1; i >=0 ; i--) {
            String trim = splits[i].trim();
            if (trim.equals("")) continue;
            sb.append(trim);
            if (i!=0) sb.append(" ");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        ReverseWordsInSentence Main = new ReverseWordsInSentence();
        System.out.println(Main.reverseWords("i am a   student!"));
    }
}
